<template>
    <alertBox data-title="批量投保" :isCloseType="true" @close="onCallback">
        <div class="process">
            <!-- ,{whichStep === 0 ? 'active' : '' , } -->
            <div :class="[whichStep === 0 ? 'active' : '', 'process-box']">
                <div class="no">
                    <i class="el-icon el-icon-check" />
                </div>
                <span>上传文件</span>
            </div>
            <div class="arrow">
                <i class="el-icon el-icon-arrow-right" />
            </div>
            <div :class="[whichStep === 1 ? 'active' : '', 'process-box']">
                <div class="no">
                    2
                </div>
                <span>确认信息</span>
            </div>
            <div class="arrow">
                <i class="el-icon el-icon-arrow-right" />
            </div>
            <div :class="[whichStep === 2 ? 'active' : '', 'process-box']">
                <div class="no">
                    3
                </div>
                <span>查看结果</span>
            </div>
        </div>

        <div class="box-block form" v-if="whichStep === 0">
            <!-- application/vnd.openxmlformats-officedocument.spreadsheetml.sheet -->
            <el-upload class="upload-demo" :drag="!fileList.length"
                :disabled="!!fileList.length && !!fileFormatErroe.length" :show-file-list="false" :file-list="fileList"
                :before-upload="onUpFile" :http-request="() => { }" accept=".xlsx" action="">
                <div class="row">
                    <div class="row">
                        <div class="key">
                            <span class="important">*</span>
                            <span>投保数据</span>
                        </div>
                        <div class="value" style="
                                display: flex;
                                align-items: center;
                                flex: auto;
                            ">
                            <button class="btn import-btn">
                                <i class="el-icon el-icon-upload2" />导入
                            </button>
                            <div class="tipsText">
                                或拖拽至此处
                            </div>
                            <a class="down-templete" style="position: relative;z-index:10"
                                href="https://bullet001.oss-cn-shanghai.aliyuncs.com/file/template/template_wesure.xlsx"
                                @click.stop="() => {
                                    return;
                                }
                                    ">模板下载</a>
                            <div v-if="fileList.length" :class="[fileList[0].name ? 'fileInfo' : '']">
                                {{ fileList[0].name ? "" + "文件名" : "" }}
                                <span style="color:#1989fa">
                                    {{ fileList[0].name }}
                                </span>
                                <span :class="[fileList[0].name ? 'fileDel' : '']" @click.stop="onDeleteFile">{{
                                    fileList[0].name ? "×" : "" }}</span>
                            </div>
                        </div>
                    </div>
                    <div></div>
                </div>
                <div class="row">
                    <div class="row">
                        <div class="key">
                            <span class="important">*</span>
                            <span>被派遣单位</span>
                        </div>
                        <div class="value">
                            <el-select v-model="companyId" filterable @change="onSelectCompany" placeholder="请选择被派遣单位">
                                <el-option v-for="(item, index) in companyList" :label="item.serveCompanyName"
                                    :disabled="item.isBlacklist || item.isForbidden
                                        " :value="item.id" v-bind:key="index">{{ item.serveCompanyName }}</el-option>
                            </el-select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="key">
                            <span class="important">*</span>
                            <span>投保方案</span>
                        </div>
                        <div class="value">
                            <el-select v-model="planIndex" filterable placeholder="请选择投保方案" @change="onSelectInsure">
                                <el-option v-for="(item, index) in planList" :label="item.industryPlanName"
                                    :value="index" :key="index" />
                            </el-select>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="row">
                        <div class="key">
                            <span class="important">*</span>
                            <span>总金额</span>
                        </div>
                        <div class="value">
                            <el-input placeholder="上传表单后自动填充" disabled name="totalAmount" :value="(userList.length * planPrice).toFixed(2)
                                " />
                        </div>
                    </div>
                    <div class="row">
                        <div class="key">
                            <span class="important">*</span>
                            <span>总人数</span>
                        </div>
                        <div class="value">
                            <el-input placeholder="上传表单后自动填充" disabled name="totalNumber" :value="userList.length" />
                        </div>
                    </div>
                </div>
                <el-button class="btn mini-btn" type="primary" :disabled="!userList.length || !planId || errorList.length > 0
                    " @click.stop="nextStep">下一步</el-button>
            </el-upload>
        </div>
        <div class="form-error" v-if="errorList.length > 0">
            <el-alert :title="`本次上传文件共发现${errorList.length}处错误,请修改后重新上传`
                " type="error" center show-icon />
            <div class="error-table">
                <el-table :data="errorList" :header-row-style="{ color: 'black' }" :row-style="{ border: 'none' }">
                    <el-table-column prop="rowNum" label="行号" width="100px" />
                    <el-table-column prop="userName" label="姓名" width="100px" />
                    <el-table-column prop="idCard" label="身份证号" width="150px" />
                    <el-table-column prop="alreadyInsured" label="错误信息" width="100px">
                        <template #default="scope">
                            <p>
                                {{ scope.row.errorMsg }}
                            </p>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="isIdCardError" label="身份证是否有误" width="100px" >
                    <template #default="scope">
                        <p>
                    {{scope.row.isIdCardError ==true? '是':'否'}}
                        </p>
                    </template>
                 </el-table-column>
                 <el-table-column prop="idCard" label="操作" width="100px" >
                    <template #default="scope">
                        <p class="link-delete" @click="onFileDelete(scope.row.idCard)">
                          删除
                        </p>
                    </template>
                </el-table-column> -->
                </el-table>
            </div>
        </div>
        <!-- 确认发薪 -->
        <div class="box-block enclosure" v-if="whichStep === 1">
            <div class="form-left">
                <div class="info-title">
                    投保数据单
                </div>
                <el-scrollbar max-height="430px">
                    <!-- <img src="@/assets/xlsx/xlsx-template.png" class="xlsx-img"/> -->
                    <el-table :data="userList" :row-class-name="tableRowClassName" style="width: 100%"
                        :header-row-style="{ color: '#202536' }" :row-style="{ color: '#5E617D' }" :cell-style="{
                            height: '35px',
                            padding: '0'
                        }">
                        <el-table-column type="index" label="序号" width="50" />
                        <el-table-column width="80" label="姓名">
                            <template #default="scope">
                                <p v-if="editIndex !== scope.$index">
                                    {{ scope.row.userName }}
                                </p>
                                <p v-else>
                                    <el-input placeholder="姓名" v-model="scope.row.userName" />
                                </p>
                            </template>
                        </el-table-column>
                        <el-table-column prop="idCard" label="身份证号" width="170">
                            <template #default="scope">
                                <p v-if="editIndex !== scope.$index">
                                    {{ scope.row.idCard }}
                                </p>
                                <p v-else>
                                    <el-input placeholder="身份证号" v-model="scope.row.idCard" />
                                </p>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="70">
                            <template #default="scope">
                                <div class="link-box">
                                    <p class="link" @click="onFileEdit(scope.$index)">
                                        {{
                                            editIndex === scope.$index
                                                ? "保存"
                                                : "编辑"
                                        }}
                                    </p>
                                    <!-- 产品改动 -->
                                    <!-- <p
                                 class="link-delete"
                                 @click="onFileDelete(scope.$index)"
                                >
                                    删除
                                </p> -->
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-scrollbar>
                <el-pagination class="pagination" layout="prev, pager, next" @current-change="handleCurrentChange"
                    :page-size="100" :total="userList.length"></el-pagination>
            </div>
            <div class="form-right">
                <div class="info-title">
                    确认信息
                </div>
                <div class="info-enclosure-name parallel">
                    <div class="info-left">
                        附件名称：
                    </div>
                    <div class="info-right">
                        {{ fileList[0].name }}
                    </div>
                </div>
                <div class="info-people-num parallel">
                    <div class="info-left">
                        总人数：
                    </div>
                    <div class="info-right">{{ userList.length }}人</div>
                </div>
                <div class="info-total-money parallel">
                    <div class="info-left">
                        总金额：
                    </div>
                    <div class="info-right info-right-num">
                        ￥{{ (userList.length * planPrice).toFixed(2) }}
                    </div>
                </div>
                <div class="parallel" style="justify-content: space-between">
                    <button class="btn-white" @click="onReset()">
                        重新选择
                    </button>
                    <button class="btn" @click="onAddInsurePay">
                        确认添加
                    </button>
                </div>
            </div>
        </div>
        <div class="box-block result" v-if="whichStep === 2">
            <img src="@/assets/xlsx/success.png" alt="" class="result-success" />
            <div class="result-title">
                提交投保成功
            </div>
            <!-- <div class="result-name">
                预计两小时内到账
            </div> -->
            <button class="btn" @click="onCloseEject">返回列表</button>
            <div class="result-info">
                <div class="info-enclosure-name parallel">
                    <div class="info-left">
                        附件名称：
                    </div>
                    <div class="info-right">
                        {{ fileList[0].name }}
                    </div>
                </div>
                <div class="info-people-num parallel">
                    <div class="info-left">
                        总人数：
                    </div>
                    <div class="info-right">{{ userList.length }}人</div>
                </div>
                <div class="info-total-money parallel">
                    <div class="info-left">
                        总金额：
                    </div>
                    <div class="info-right info-right-num">
                        ￥{{ (userList.length * planPrice).toFixed(2) }}
                    </div>
                </div>
            </div>
        </div>
    </alertBox>
    <!-- 导入名单格式错误弹窗 -->
    <el-dialog v-model="isFormError" width="450px" title="名单格式错误人员" center @close="onFormError">
        <div class="edit-popup-box">
            <div class="row row-uninsured" v-for="(item, index) in fileFormatErroe" v-bind:key="index">
                <div>姓名：{{ item.name }} 身份证：({{ item.code }})</div>
            </div>
        </div>
    </el-dialog>
</template>

<script lang="ts">
import user from '@/utils/user'
import { defineComponent } from 'vue'
import {
    getInsureCompanyList,
    getInsurePlanList,
    InsuranceCompanyDto,
    PlanDto,
    batchInsure,
    insureInfoProjectNum,
    UserInfoDTOList,
    getInsured,
    searchCompanyDetailInfoApi
} from '@/api/insure-deduction'
import alertBox from './alert-box.vue'
import ExcelJS from 'exceljs'
import { looseIndexOf } from '@vue/shared'
import { number } from 'echarts'
import { formTesting, FormTestingErroeDto } from '@/utils/util'
import { ElMessage } from 'element-plus'
export default defineComponent({
    props: ['close'],
    components: { alertBox },
    data() {
        return {
            isDis1: false,
            isDis2: false,
            whichStep: 0,
            planName: '', // 投保方案名称
            planId: '' as string | number, // 投保方案Id
            planPrice: 0, // 投保方案价格
            planWesureType: '',
            planWesureName: '',
            planIndex: '',
            planList: [] as PlanDto[], // 投保方案列表
            conpanyName: '', // 投保企业名称
            companyId: '' as string | number, // 投保企业ID
            companyList: [] as any,
            fileList: [] as { name: string }[],
            userList: [] as {
                idCard: string;
                userName: string;
            }[],
            fileContentList: [] as {
                idCard: string;
                userName: string;
            }[],
            isOnBtn: true,
            dom: '',
            pageNum: 1,
            pageSize: 100,
            editIndex: '' as string | number,
            userIndex: 0,
            errorList: [] as {
                rowNum: number;
                alreadyInsured: boolean;
                isIdCardErrow: boolean;
                userName: string;
                idCard: string;
            }[], // 错误数据列表
            projectNum: 0,
            fileErrorList: [] as number[],
            fileFormatErroe: [] as { name: string; code: string }[],
            isFormError: false
        }
    },
    async created() {
        await this.getInsureCompanyList()
        // await this.searchCompanyDetailInfo(user.companyName, 1)
    },
    methods: {
        async nextStep() {
            // if (this.isDis1 || this.isDis2) {
            //     ElMessage.error('非常抱歉，当前方案仅支持(天津市静海区以外的)地区投保，请选择"其他方案"继续投保"')
            //     return
            // }
            if (this.fileErrorList.length > 0) {
                this.$message.error(
                    '(' +
                    this.fileErrorList.toString() +
                    ')' +
                    '  ' +
                    ' 该序号下信息不完整或无信息'
                )
                return
            }
            // this.whichStep = 1
            const arr = [] as any[]
            this.userList.forEach(item => {
                console.log(item, 'item')
                if (
                    typeof item.userName === 'object' ||
                    typeof item.idCard === 'object'
                ) {
                    const obj = formTesting(item.userName, item.idCard)
                    arr.push({
                        userName: obj.name,
                        idCard: obj.code
                    })
                } else {
                    arr.push(item)
                }
            })
            console.log(arr, 'arrarr')
            this.userList = arr
            const result = await insureInfoProjectNum()
            this.projectNum = result.projectNum
            // this.userList
            const result2 = await getInsured({
                serveCompanyId: this.companyId,
                gscUserInfoDTOList: arr
            })
            this.errorList = result2
            if (this.errorList.length !== 0) {
                this.whichStep = 0
            } else {
                this.whichStep = 1
            }
            this.fileErrorList = []
        },
        async getInsureCompanyList() {
            const result = await getInsureCompanyList()
            this.companyList = result
        },
        // TODO 日日保天津市静海区禁止投保
        async searchCompanyDetailInfo(name: string, type: number) {
            let res = await searchCompanyDetailInfoApi({
                throwException: false,
                keyword: name
            })
            console.log(res, 'fasdugbyfgyusdguy')
            if (res.district === '静海区' && res.city === '天津市') {
                ElMessage.error('非常抱歉，当前方案仅支持(天津市静海区以外的)地区投保，请选择"其他方案"继续投保"')
                if (type === 1) {
                    this.isDis1 = true
                } else if (type === 2) {
                    this.isDis2 = true
                }
            } else {
                if (type === 1) {
                    this.isDis1 = false
                } else if (type === 2) {
                    this.isDis2 = false
                }
            }
        },
        async onSelectCompany(e: number) {
            // TODO
            console.log(e, this.companyList, 'ghfusghy')
            // this.companyList.forEach((item: any) => {
            //     if (e === item.id) {
            //         console.log(1)
            //         this.searchCompanyDetailInfo(item.serveCompanyName, 2)
            //     }
            // })
            this.companyList.forEach((item: any, i: number) => {
                if (e === item.id && (item.isBlacklist || item.isForbidden)) {
                    this.companyId = ''
                }
            })
            if (this.companyId) {
                this.planList = await getInsurePlanList({
                    serveCompanyId: this.companyId as number,
                    productType: 0
                })
            } else {
                this.planList = []
            }
            this.planIndex = ''
            this.planId = ''
            this.planPrice = 0
            this.planName = ''
        },
        async onUpFile(file: File) {
            console.log(file, 'file')
            // if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
            //     this.$message.error('请上传xlsx格式')
            //     return
            // }
            if (!file?.name?.endsWith('.xlsx')) {
                this.$message.error('请上传xlsx格式')
                return
            }
            //  as { userName: string; idCard: string }[]
            const userList = [] as { userName: string; idCard: string }[]
            const reader = new FileReader()
            reader.onload = async e => {
                const workbook = new ExcelJS.Workbook()
                await workbook.xlsx.load(
                    (e.target as FileReader).result as ArrayBuffer
                )
                workbook.getWorksheet(1).eachRow((item, index) => {
                    const fileError = formTesting(
                        item.getCell(2).value as string | FormTestingErroeDto[],
                        item.getCell(3).value as string | FormTestingErroeDto[]
                    )
                    console.log(fileError, 'fileError')
                    this.fileFormatErroe.push(fileError)
                    if (index <= 2) {
                        return item
                    }
                    if (item.getCell(2).value && item.getCell(3).value) {
                        console.log(item.getCell(2).value, 'item')
                        userList.push({
                            userName: item.getCell(2).value as string,
                            idCard: item.getCell(3).value as string
                        })
                    } else {
                        this.fileErrorList.push(
                            item.getCell(1).value
                                ? Number(item.getCell(1).value)
                                : 0
                        )
                    }
                })
                this.fileFormatErroe = this.fileFormatErroe.filter(
                    item => item.name
                )
                // if (this.fileFormatErroe.length > 0) {
                //     this.isFormError = true
                //     return this.fileFormatErroe.length
                // }
                for (let i = 0; i < userList.length; i++) {
                    for (let j = i + 1; j < userList.length; j++) {
                        if (userList[i].idCard === userList[j].idCard) {
                            userList.splice(j, 1)
                            j = j - 1
                        }
                    }
                }
                console.log(userList, 'userList')
                this.userList = userList
                console.log(this.userList, 'this.userList')
                this.handleCurrentChange(1)
                this.fileList.push({
                    name: file.name
                })
            }
            reader.readAsBinaryString(file)
        },
        // 选择方案
        onSelectInsure(index: number) {
            this.planId = this.planList[index].id
            this.planPrice = this.planList[index].price
            this.planWesureType = this.planList[index].wesurePlanCode
            this.planWesureName = this.planList[index].industryPlanName
        },
        tableRowClassName(row: { row: { isError: boolean } }) {
            console.log(row.row.isError)
            if (row.row.isError) {
                return 'warm-row'
            }
            return ''
        },
        // 上传文件编辑
        onFileEdit(event: number) {
            if (this.editIndex !== '' && this.editIndex !== event) {
                this.$message.error('请先保存')
                return
            }
            if (this.editIndex === event) {
                this.editIndex = ''
                // 按当前页删除一百条替换
                this.userList.splice(
                    (this.pageNum - 1) * 100,
                    100,
                    ...this.userList
                )
                console.log(this.userList)
            } else {
                this.editIndex = event
            }
        },
        onFileDelete(event: string) {
            console.log(event, 'eventevent')
            const arr = this.userList.map(item => {
                return item.idCard + ''
            })
            const arr2 = this.errorList.map(item => {
                return item.idCard
            })
            const index = arr.indexOf(event)
            const index2 = arr2.indexOf(event)
            this.userList.splice(index, 1)
            this.errorList.splice(index2, 1)
        },
        // 翻页
        handleCurrentChange(event: number) {
            this.pageNum = event
            this.fileContentList = this.userList.slice(
                (this.pageNum - 1) * 100,
                this.pageNum * 100
            )
            console.log(this.fileContentList, 'fileContentList')
        },
        async onAddInsurePay() {
            const result = await batchInsure({
                industryPlanId: this.planId as string,
                serveCompanyId: this.companyId as number,
                wesureType: this.planWesureType,
                wesureTypeName: this.planWesureName,
                userList: this.userList,
                projectNum: this.projectNum
            })
            if (result.code && result.code === 2) {
                this.$message.error(result.data)
                setTimeout(async () => {
                    this.whichStep -= 1
                    const result = await getInsured({
                        serveCompanyId: this.companyId,
                        gscUserInfoDTOList: this.userList
                    })
                    this.errorList = result
                }, 2000)
                return
            }
            this.whichStep += 1
        },
        onCloseEject() {
            this.$emit('close')
            this.$emit('complete')
        },
        onDeleteFile() {
            this.userList = []
            this.fileList = []
            this.fileErrorList = []
            this.errorList = []
            this.$message.success('删除成功')
        },
        onReset() {
            this.whichStep -= 1
            this.userList = []
            this.fileList = []
        },
        // 错误名单关闭回调
        onFormError() {
            this.fileFormatErroe = []
            console.log('弹窗关闭回调')
        },
        onCallback() {
            console.log('回调')
            this.$emit('close')
        }
    }
})
</script>

<style scoped lang="stylus">
// 弹窗样式
eject()
ejectFrom()
:deep() .container-c
    width 950px
.process
    width 820px
.box-block
    width 820px
.value
    width 240px !important
.el-input--prefix .el-input__inner
    width 240px !important
:deep() .el-upload-dragger
    width 100%
    height 100%
    border-color transparent
:deep().el-upload.el-upload--text
    width 100%
.tipsText
    margin-left 10px
.mini-btn
    margin 10px auto
    width 100px
.fileInfo
    margin-left 20px
    border 1px solid #f4f4f5
    padding 2px 7px
    border-radius 13px
    display flex
    align-items center
    background #f4f4f5
    .fileDel
        border-radius 44px
        border 2px solid #ccc
        width 15px
        height 15px
        line-height 15px
        text-align center
        display block
        color #ccc
        margin-left 5px
.error-table
    width 90%
    margin 0 auto
.form-left
    margin-top 16px
    width 450px
    height 312px
/deep/.el-table__body, /deep/.el-table__header{
    width 100% !important
}
/deep/.el-table--scrollable-y .el-table__body-wrapper {
   overflow-y clip
}
// .el-table td.el-table__cell div
//     white-space pre-wrap
// .table-column-alone
//     width 100px
.el-scrollbar__wrap
    overflow auto
    height 100%
.el-pagination{
    float right
}
.el-table>>>.warm-row {
  background #fdf6ec
  color white
}
.link-box{
    display:flex;
    justify-content: space-between;
    width: auto;
}
.link-delete{
    color:red;
}
</style>
